<template>
  <a-spin :spinning='confirmLoading'>
    <j-form-container :disabled='formDisabled'>
      <a-form :form='form' slot='detail'>
        <a-row>
          <!-- <a-col :span="12">
            <a-form-item label="投标项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                v-decorator="['projectNum', validatorRules.projectNum]"
                placeholder="请输入投标名称"
                style="width: 100%"
              />
            </a-form-item>
          </a-col> -->
          <a-col :span='12'>
            <a-form-item label='投标项目名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['name', validatorRules.name]" placeholder='请输入投标名称' style='width: 100%' />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='商机名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                v-decorator="['opportunityName', validatorRules.opportunityName]"
                :trigger-change='true'
                org-fields='id,name,customer_name,num'
                dest-fields='opportunityId,opportunityName,customerName,opportunityNum'
                code='bus_business_opportunity_select'
                :param='{ saleLeader: $store.getters.userInfo.realname }'
                @callback='popupCallback'
              />
            </a-form-item>
            <a-form-item v-show='false'>
              <a-input v-decorator="['opportunityId']" />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='客户名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['customerName']" disabled placeholder='请先选择商机名称'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='商机编号' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['opportunityNum']" disabled placeholder='请先选择商机名称'></a-input>
            </a-form-item>
          </a-col>

          <a-col :span='12'>
            <a-form-item label='投标报价' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['bidQuote', validatorRules.bidQuote]"
                placeholder='请输入投标报价'
                style='width: 100%'
                :min='0'
                type='number'
                @focus="clearInput('bidQuote')"
                @change='getGrossProfit'
              >
                <span slot='addonAfter'>元</span>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='采购费A' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['purchasea']"
                placeholder='请先输入采购明细'
                style='width: 100%'
                :min='0'
                type='number'
                @focus="clearInput('purchasea')"
                @change='getGrossProfit'
                disabled
              >
                <span slot='addonAfter'>元</span>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='采购费B' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['purchaseb', validatorRules.purchaseb]"
                placeholder='请输入采购费B'
                style='width: 100%'
                :min='0'
                type='number'
                @focus="clearInput('purchaseb')"
                @change='getGrossProfit'
              >
                <span slot='addonAfter'>元</span>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='税费' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['taxation', validatorRules.taxation]"
                placeholder='请输入税费'
                style='width: 100%'
                :min='0'
                type='number'
                @focus="clearInput('taxation')"
                @change='getGrossProfit'
              >
                <span slot='addonAfter'>元</span>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='中标服务费' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['bidServiceCharge', validatorRules.bidServiceCharge]"
                placeholder='请输入中标服务费'
                style='width: 100%'
                :min='0'
                type='number'
                @focus="clearInput('bidServiceCharge')"
                @change='getGrossProfit'
              >
                <span slot='addonAfter'>元</span>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='投标费用' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['bidCost', validatorRules.bidCost]"
                placeholder='请输入投标费用'
                style='width: 100%'
                :min='0'
                type='number'
                @focus="clearInput('bidCost')"
                @change='getGrossProfit'
              >
                <span slot='addonAfter'>元</span>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='预计毛利' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['grossProfit']" placeholder='预计毛利' style='width: 100%' disabled />
              <span slot='addonAfter'>元</span>
            </a-form-item>
          </a-col>
          <a-col v-if='showFlowSubmitButton' :span='24' style='text-align: center'>
            <a-button @click='submitForm' type='primary'>提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
    <a-tabs v-model='activeKey' @change='handleChangeTabs'>
      <a-tab-pane tab='采购明细' :key='refKeys[0]' :forceRender='true'>
        <j-editable-table
          :ref='refKeys[0]'
          :loading='BidProjectFormTable.loading'
          :columns='BidProjectFormTable.columns'
          :dataSource='BidProjectFormTable.dataSource'
          :maxHeight='300'
          :disabled='formDisabled'
          :rowNumber='true'
          :actionButton='true'
          @valueChange='tableValueChange'
        >
          <template v-slot:action='props'>
            <a @click='handleDelete(props)' :disabled='formDisabled'
               style='width: 100%; display: inherit; text-align: center'
            >
              <a-icon type='close' style='color: red; font-size: 18px'></a-icon
              >
            </a>
          </template>
        </j-editable-table>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { FormTypes, getRefPromise } from '@/utils/JEditableTableUtil'
import { toFixedTwo } from '@/utils/util'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'

export default {
  name: 'BidProjectForm',
  mixins: [JEditableTableMixin],
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      // form: this.$form.createForm(this),
      addDefaultRowNum: 1,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        name: {
          rules: [{ required: true, message: '请输入项目名称!' }]
        },
        opportunityName: {
          rules: [{ required: true, message: '请选择商机名称!' }]
        },
        bidQuote: {
          initialValue: 0,
          rules: [
            { required: true, message: '请输入投标报价!' },
            { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
          ]
        },
        purchasea: {
          initialValue: 0,
          rules: [
            { required: true, message: '请输入采购费A!' },
            { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
          ]
        },
        purchaseb: {
          initialValue: 0,
          rules: [
            { required: true, message: '请输入采购费B!' },
            { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
          ]
        },
        taxation: {
          initialValue: 0,
          rules: [
            { required: true, message: '请输入税费!' },
            { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
          ]
        },
        bidServiceCharge: {
          initialValue: 0,
          rules: [
            { required: true, message: '请输入中标服务费!' },
            { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
          ]
        },
        bidCost: {
          initialValue: 0,
          rules: [
            { required: true, message: '请输入投标费用!' },
            { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
          ]
        },
        projectNum: {
          rules: [{ required: true, message: '请输入投标编号!' }]
        },
        opportunityId_dictText: {
          rules: [{ required: true, message: '请输入商机名称!' }]
        }
      },
      BidProjectFormTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '货物名称',
            required: true,
            key: 'goodsName',
            type: FormTypes.input,
            dictCode: 'icm_payment_collection_condition',
            placeholder: '请输入${title}',
            defaultValue: '',
            width: '40%',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '规格型号',
            required: true,
            key: 'model',
            type: FormTypes.input,
            placeholder: '请输入${title}',
            defaultValue: '',
            width: '25%',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          // {
          //   title: '供应商',
          //   required: true,
          //   key: 'supplierName',
          //   type: FormTypes.popup,
          //   placeholder: '请选择${title}',
          //   popupCode: 'contract_supplier_select',
          //   orgFields: 'id,name',
          //   destFields: 'supplierId,supplierName',
          //   fields: 'supplierName',
          //   defaultValue: '',
          //   width: '30%',
          //   validateRules: [{ required: true, message: '${title}不能为空' }],
          // },
          // {
          //   title: '供应商id',
          //   key: 'supplierId',
          //   type: FormTypes.hidden,
          // },
          {
            title: '供应商id',
            key: 'supplierId',
            type: FormTypes.hidden
          },
          {
            title: '数量',
            required: true,
            key: 'amount',
            type: FormTypes.inputNumber,
            placeholder: '请输入${title}',
            width: '10%',
            validateRules: [{ required: true, message: '${title}不能为空' }, { pattern: /^[1-9]\d*$/, message: '请输入数字!' }]
          },
          {
            title: '单价(元)',
            required: true,
            key: 'unitPrice',
            width: '10%',
            type: FormTypes.inputNumber,
            placeholder: '请输入单价',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '总价',
            required: false,
            disabled: true,
            key: 'totalPrice',
            width: '10%',
            type: FormTypes.inputNumber
          },
          {
            title: '操作',
            key: 'action',
            width: '5%',
            type: FormTypes.slot,
            slotName: 'action'
          }
        ]
      },
      refKeys: ['BidProjectFormTable'],
      tableKeys: ['BidProjectFormTable'],
      activeKey: 'BidProjectFormTable',
      url: {
        add: '/bid/bidProject/add',
        edit: '/bid/bidProject/edit',
        queryById: '/bid/bidProject/queryById',
        purchaseItem: {
          list: '/bid/bidProject/queryPurchaseItemByMainId'
        }
      },
      fields: [
        'applicant',
        'bidQuote',
        'purchasea',
        'purchaseb',
        'purchase',
        'supplierId',
        'name',
        'projectNum',
        'taxation',
        'bidServiceCharge',
        'grossProfit',
        'opportunityId',
        'bpmStatus',
        'opportunityName',
        'opportunityNum',
        'customerName',
        'projectNum',
        'bidCost'
      ]
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  mounted() {
    this.getGrossProfit()
  },
  methods: {
    handleDelete(props) {
      let { rowId, target } = props
      target.removeRows(rowId)
      // console.log(props.getValue())
      this.getValues()
    },
    tableValueChange({ row }) {
      if (row.amount && row.unitPrice) {
        let totalPrice = toFixedTwo(row.amount * row.unitPrice)
        this.$refs.BidProjectFormTable.setValues([{ rowKey: row.id, values: { totalPrice } }])
        this.getValues()
      } else {
        this.form.setFieldsValue({ purchasea: 0 })
      }
    },
    getValues() {
      this.$refs.BidProjectFormTable.getValues((error, value) => {
        let count = 0
        value.forEach((v) => {
          if (v.totalPrice) {
            count += +v.totalPrice
          }
        })
        this.form.setFieldsValue({ purchasea: toFixedTwo(count) })
        this.getGrossProfit()
      })
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      let fieldval = pick(this.model, this.fields)
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.purchaseItem.list, params, this.BidProjectFormTable)
      }
    },
    clearInput(data) {
      if (this.form.getFieldValue(data) == 0) {
        this.form.setFieldsValue({ [data]: '' })
      }
    },
    // 计算毛利
    getGrossProfit() {
      this.$nextTick(() => {
        let bidQuote = this.form.getFieldValue('bidQuote') || 0
        let purchasea = this.form.getFieldValue('purchasea') || 0
        let purchaseb = this.form.getFieldValue('purchaseb') || 0
        let taxation = this.form.getFieldValue('taxation') || 0
        let bidServiceCharge = this.form.getFieldValue('bidServiceCharge') || 0
        let bidCost = this.form.getFieldValue('bidCost') || 0
        let grossProfit = bidQuote - purchasea - purchaseb - taxation - bidServiceCharge - bidCost
        this.form.setFieldsValue({ grossProfit: grossProfit.toFixed(2) })
      })
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        purchaseItemList: allValues.tablesValue[0].values
      }
    },
    // add() {
    //   this.edit({})
    // },
    // edit(record) {
    //   this.form.resetFields()
    //   this.model = Object.assign({}, record)
    //   this.visible = true
    //   this.$nextTick(() => {
    //     this.form.setFieldsValue(pick(this.model, this.fields))
    //   })
    // },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    submitForm() {
      const that = this
      return new Promise(((resolve, reject) => {
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            console.log('表单提交数据', formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                resolve(true)
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
            })
          } else {
            this.$store.commit('BPM_SUBMIT_STATES', {})
          }
        })
      }))
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, this.fields))
    }
  },
  watch: {
    'BidProjectFormTable.dataSource': {
      deep: true,
      handler: (value) => {
        value.forEach((val) => {
          val.totalPrice = toFixedTwo(val.amount * val.unitPrice)
        })
      }
    },
    '$store.state.bpm.bpmSubmitStates': {
      immediate: true,
      handler(val) {
        if (val && val.edit && val.edit === '1') {
          this.submitForm().then(res => {
            if (res) {
              this.$store.commit('BPM_SUBMIT_STATES', {edit: '2'})
            }
          })
        }
      },
    }
  }
}
</script>